<script lang="ts" setup>
import type { Dict } from '@croco/framework/types';

import { onBeforeMount, ref } from 'vue';

import { Page } from '@croco/framework/libraries';

import { getDictTrim } from '#/api';
import { service } from '#/api/request';
import { DataTable } from '#/components/data-table';

import { useTable } from './data';
import Edit from './edit.vue';

defineOptions({ name: 'SystemNotice' });

const dataTableRef = ref<InstanceType<typeof DataTable>>();
const editRef = ref<InstanceType<typeof Edit>>();
const enums = reactive<{
    status: Array<Dict> | undefined;
    type: Array<Dict> | undefined;
}>({
    status: undefined,
    type: undefined,
});
const columns = useTable(enums, ({ code, scope }) => {
    switch (code) {
        case 'edit': {
            onEdit(scope.row);
            break;
        }
        case 'remove': {
            onDelete([scope.row]);
            break;
        }
        default: {
            break;
        }
    }
});

// 表单
function onEdit(row?: any) {
    editRef.value?.open({
        data: row,
        success: dataTableRef.value?.refresh,
    });
}

// 删除
function onDelete(rows: { id: number }[]) {
    const ids = rows.map((item) => item.id);
    service.confirm({
        message: `确定对所选记录进行${ids.length === 1 ? '删除' : '批量删除'}操作,该操作不可逆?`,
        url: '/system/notice',
        data: { id: ids },
        success: dataTableRef.value?.refresh,
    });
}

onBeforeMount(() => {
    // 获取字典数据
    getDictTrim(['sys_notice_type', 'sys_notice_status']).then((rs) => {
        enums.type = rs[0] ?? [];
        enums.status = rs[1] ?? [];
    });
});
</script>
<template>
    <Page auto-content-height>
        <DataTable ref="dataTableRef" :columns="columns" api="/system/notice" selection select-on-row-click>
            <template #extra="{ selections }">
                <el-button v-auth="'system:config:add'" @click="onEdit()" />
                <el-button v-auth="'system:config:remove'" @click="onDelete(selections)" :disabled="selections.length <= 0" type="danger" />
            </template>
            <template #type="{ form }">
                <el-select v-model="form.type" :empty-values="[null, undefined]">
                    <el-option label="全部" value="" />
                    <el-option v-for="(item, index) in enums.type" :key="index" :label="item.label" :value="item.value" />
                </el-select>
            </template>
            <template #status="{ form }">
                <el-select v-model="form.status" :empty-values="[null, undefined]">
                    <el-option label="全部" value="" />
                    <el-option v-for="(item, index) in enums.status" :key="index" :label="item.label" :value="item.value" />
                </el-select>
            </template>
        </DataTable>

        <Edit ref="editRef" :enums="enums" />
    </Page>
</template>
